package com.example.printscreen.printscreen.network;

import android.content.Intent;

import com.example.printscreen.printscreen.BaseApplication;
import com.example.printscreen.printscreen.MainActivity;
import com.example.printscreen.printscreen.bean.LoginUser;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 添加统一参数
 * verify验证参数
 * token头
 *
 * 如果只有token的话,也可以直接在NetworkRequest添加
 *
 * author: xiaoluo
 * date: 2017-03-15 10:45
 */
public class TupaiInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        HttpUrl url;

        url = original.url().newBuilder()
                .build();

        // 添加token
        Request request = original.newBuilder()
                .addHeader("token", LoginUser.TokenVerity.getToken() + "")
                .method(original.method(), original.body())
                .url(url)
                .build();

        Response response = chain.proceed(request);
        // 登录态失效拦截
        if (response.code() == 401) {
            LoginUser.TokenVerity.setToken("");
            Intent intent = new Intent(BaseApplication.getAppContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BaseApplication.getAppContext().startActivity(intent);
            throw new APIException("登录态失效");
        } else if (response.code() == 500) {
            throw new APIException("请求出了点问题");
        }
        return response;
    }
}

